<?php

namespace app\models;

use Yii;
use Faker\Provider\Uuid;

/**
 * This is the model class for table "user_login".
 *
 * @property string $id
 * @property string $user_id 用户id
 * @property string $ip ip
 * @property string $device 设备号
 * @property string $token token
 * @property string $created_at
 */
class UserLogin extends Base
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user_login';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_id', 'login_type', 'ip', 'created_at'], 'integer'],
            [['device'], 'string', 'max' => 256],
            [['token'], 'string', 'max' => 64],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'ip' => 'Ip',
            'device' => 'Device',
            'token' => 'Token',
            'created_at' => 'Created At',
        ];
    }

    public static function generateToken($login_type=1){
        $login = new UserLogin();
        $login->token = Uuid::uuid();
        $login->ip = ip2long(Yii::$app->request->userIP);
        $login->device = Yii::$app->request->userAgent;
        $login->login_type = $login_type;
        if(!$login->save()){
            Tool::log($login->errors);
        }
        return $login->token;
    }
}
